'use strict';

const Service = require('egg').Service;
const { Op } = require('sequelize');

class ArticleService extends Service {
  // 创建文章
  async create(data) {
    const { app } = this;
    return await app.model.Article.create(data);
  }

  // 删除文章
  async destroy(id, userId) {
    const { app } = this;
    const article = await app.model.Article.findByPk(id);
    if (!article) return false;

    // 检查是否为作者
    if (article.user_id !== userId) return false;

    await article.destroy();
    return true;
  }

  // 更新文章
  async update(id, data, userId) {
    const { app } = this;
    const article = await app.model.Article.findByPk(id);
    if (!article) return null;

    // 检查是否为作者
    if (article.user_id !== userId) return null;

    await article.update(data);
    return article;
  }

  // 根据ID查找文章
  async findById(id) {
    const { app } = this;
    return await app.model.Article.findByPk(id, {
      include: [{
        model: app.model.User,
        attributes: ['id', 'name', 'email'],
        as: 'user',
      }],
    });
  }

  // 查找文章列表
  async findList({ page, pageSize, status, title }) {
    const { app } = this;
    const where = {};
    if (status !== undefined) {
      where.status = status;
    }
    if (title) {
      where.title = { [Op.like]: `%${title}%` };
    }

    const offset = (page - 1) * pageSize;
    const { count, rows } = await app.model.Article.findAndCountAll({
      where,
      include: [{
        model: app.model.User,
        attributes: ['id', 'name', 'email'],
        as: 'user',
      }],
      order: [['created_at', 'DESC']],
      limit: pageSize,
      offset,
    });

    return {
      total: count,
      list: rows,
      page,
      pageSize,
      totalPages: Math.ceil(count / pageSize),
    };
  }
}

module.exports = ArticleService;